Closure in Javascript




Closure is the one that contains inner function which can access the variables and parameters of the outer function even after the outer function has returned.

To know more, we should first know what is nested function in javascript. So let's look into it first. Any function that enclosed inside an other function it is called inner function. The inner function can now access the variables of the outer function. Let's see it with an example program.

This will return the result as 1

In the above program, we have a function counter() which acts as outer function and increment() function which acts as inner function.

We have a variable _counter which belongs to outer function counter() which will be incremented everytime the increment function is called.

Whenever we call the counter function, it initializes the _counter variable to 0 and call increment function to increment the _counter variable by 1 and return 1 as result.

Basically, every time when you call the function it is going to return the result as 1. In order to make it increment everytime when we call the function, we have to modify the code and make it as a closure function.

This will return the result as below in the console.

1
2
3

In the above program, the counter() function instead of returning the _counter value it returns the reference to increment() function.

Now we call the counter() function and assign it to incrementCounter variable. Then later on whenever we call incrementCounter() function since it holds the reference to increment function the value gets incremented.

What is the need for Closure?

Closure allows a function to have private variables and it can be also useful we need to avoid global variable declaration. If we want any variable to be available to many functions usually we will declare the variable as global variable. To avoid declaring a variable as global variable we can use closure to restrict declaring a variable globally.


Most Read